package com.ruoyi.framework.web.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pay.domain.PayCoinUserForm;
import com.ruoyi.pay.service.IPayCoinUserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wq.domain.WqGameHome;
import com.ruoyi.wq.domain.WqUserGame;
import com.ruoyi.wq.domain.vo.WqGameHomeVO;
import com.ruoyi.wq.service.IWqGameHomeService;
import com.ruoyi.wq.service.IWqUserGameService;
import com.ruoyi.wx.domain.WxMpMsgForm;
import com.ruoyi.wx.service.WxMsgService;

import cn.hutool.core.date.DateUtil;

@Component
public class GameHomeService {
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private IWqGameHomeService wqGameHomeService;
	
	@Autowired
	private IWqUserGameService wqUserGameService;
	
	@Autowired
    private WxMsgService wxMsgService;
	
	@Autowired
    private IPayCoinUserService payCoinUserService;
	
	public void addGameHome(WqGameHomeVO wqGameHome){
		// 创建队伍需要消耗
		Integer coinNum = 0;
		Integer amount = payCoinUserService.getAmount();
		if(coinNum > amount){
			// 趣豆不足
			throw new ServiceException("创建队伍需要【"+coinNum+"】趣豆，请充值",888);
		}
		
    	Long userId = SecurityUtils.getUserId();
    	String game = wqGameHome.getGame();
    	if(StringUtils.isBlank(game)){
    		throw new ServiceException("请选择想玩分路");
    	}
    	if(RoleEnum.FUZHU.getCode().equals(game)){
    		wqGameHome.setFuzhuUserId(userId);
    	}else if(RoleEnum.SHANG.getCode().equals(game)){
    		wqGameHome.setShangUserId(userId);
    	}else if(RoleEnum.SHOOT.getCode().equals(game)){
    		wqGameHome.setShootUserId(userId);
    	}else if(RoleEnum.ZHONG.getCode().equals(game)){
    		wqGameHome.setZhongUserId(userId);
    	}else if(RoleEnum.DAYE.getCode().equals(game)){
    		wqGameHome.setDayeUserId(userId);
    	}
    	wqGameHome.setStartTime(wqGameHome.getOnlineTime().split("-")[0]);
    	wqGameHome.setUserId(SecurityUtils.getUserId());
    	wqGameHomeService.save(wqGameHome);
        
        // 加入我的组队
        WqUserGame userGame = new WqUserGame();
        userGame.setGameHomeId(wqGameHome.getId());
        userGame.setUserId(userId);
        wqUserGameService.save(userGame);
        
        QueryWrapper<WqUserGame> usWrapper = new QueryWrapper<>();
        WqUserGame ug = new WqUserGame();
        ug.setUserId(userId);
        usWrapper.setEntity(ug);
        Integer gameNum = wqUserGameService.count(usWrapper);
        SysUser sysUser = sysUserService.getById(userId);
        sysUser.setGameNum(gameNum);
        sysUserService.updateById(sysUser);
        
        PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
		payCoinUserForm.setUserId(userId);
		payCoinUserForm.setCoinNum(coinNum);
		payCoinUserForm.setCoinType("1");
		payCoinUserForm.setSourceId(wqGameHome.getId());
		payCoinUserForm.setRemark("创建队伍消费");
		payCoinUserService.savePayCoinUser(payCoinUserForm);
    }

	public void addJoin(WqGameHomeVO wqGameHome) {
		// 加入队伍需要消耗
		Integer coinNum = 0;
		Integer amount = payCoinUserService.getAmount();
		if(coinNum > amount){
			// 趣豆不足
			throw new ServiceException("加入队伍需要【"+coinNum+"】趣豆，请充值",888);
		}
		
		Long userId = SecurityUtils.getUserId();
		SysUser user = sysUserService.getById(userId);
		WqGameHome home = wqGameHomeService.getById(wqGameHome.getId());
		
		// 插入我的组队
		QueryWrapper<WqUserGame> userGameQuery = new QueryWrapper<>();
		WqUserGame entity = new WqUserGame();
		entity.setGameHomeId(home.getId());
		entity.setUserId(userId);
		userGameQuery.setEntity(entity);
		WqUserGame userGame = wqUserGameService.getOne(userGameQuery);
		if(userGame == null){
			// 校验段位是否匹配
			if(!home.getArea().equals(user.getGameArea())){
				throw new ServiceException("区服不匹配",999);
			}
			if(!home.getLevelLimit().contains(user.getGameLevel())){
				throw new ServiceException("段位不匹配",999);
			}
			
			userGame = new WqUserGame();
			userGame.setGameHomeId(home.getId());
			userGame.setUserId(userId);
			userGame.setGameName(user.getGameName());
			userGame.setGameArea(user.getGameArea());
			// 判断游戏昵称是否重复
			wqUserGameService.checkUserGame(userGame);
						
			wqUserGameService.save(userGame);
			
			QueryWrapper<WqUserGame> usWrapper = new QueryWrapper<>();
	        WqUserGame uGame = new WqUserGame();
	        uGame.setUserId(userId);
	        usWrapper.setEntity(uGame);
	        Integer gameNum = wqUserGameService.count(usWrapper);
	        user.setGameNum(gameNum);
	        sysUserService.updateById(user);
			
			if(RoleEnum.DAYE.getCode().equals(wqGameHome.getGame())){
				if(home.getDayeUserId() == null){
					home.setDayeUserId(userId);
				}else{
					throw new ServiceException("打野已被占用");
				}
			}else if(RoleEnum.FUZHU.getCode().equals(wqGameHome.getGame())){
				if(home.getFuzhuUserId() == null){
					home.setFuzhuUserId(userId);
				}else{
					throw new ServiceException("游走已被占用");
				}
			}else if(RoleEnum.ZHONG.getCode().equals(wqGameHome.getGame())){
				if(home.getZhongUserId() == null){
					home.setZhongUserId(userId);
				}else{
					throw new ServiceException("中单已被占用");
				}
			}else if(RoleEnum.SHANG.getCode().equals(wqGameHome.getGame())){
				if(home.getShangUserId() == null){
					home.setShangUserId(userId);
				}else{
					throw new ServiceException("对抗路已被占用");
				}
			}else if(RoleEnum.SHOOT.getCode().equals(wqGameHome.getGame())){
				if(home.getShootUserId() == null){
					home.setShootUserId(userId);
				}else{
					throw new ServiceException("发育路已被占用");
				}
			}
			Integer joinNum = 5;
			if(home.getShangUserId() == null){
				joinNum--;
			}
			if(home.getZhongUserId() == null){
				joinNum--;
			}
			if(home.getShootUserId() == null){
				joinNum--;
			}
			if(home.getDayeUserId() == null){
				joinNum--;
			}
			if(home.getFuzhuUserId() == null){
				joinNum--;
			}
			home.setJoinNum(joinNum);
			wqGameHomeService.updateById(home);
			
			// TODO 扣除趣币
			if(coinNum > 0){
				PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
				payCoinUserForm.setUserId(userId);
				payCoinUserForm.setCoinNum(coinNum);
				payCoinUserForm.setCoinType("1");
				payCoinUserForm.setSourceId(wqGameHome.getId());
				payCoinUserForm.setRemark("加入队伍消费");
				payCoinUserService.savePayCoinUser(payCoinUserForm);
			}
			
			// 组队成功
			entity = new WqUserGame();
			entity.setGameHomeId(home.getId());
			entity.setStatus("0");
			userGameQuery.setEntity(entity);
			List<WqUserGame> userGameList = wqUserGameService.list(userGameQuery);
			if(home.getUserNum().intValue() == userGameList.size()){
				// 房间锁定
				home.setStatus("1");
				wqGameHomeService.updateById(home);
				
				// 发送微信订阅消息
				for(WqUserGame ug : userGameList){
					SysUser su = sysUserService.getById(ug.getUserId());
					if(StringUtils.isNotBlank(su.getAppId())){
		            	if(StringUtils.isNotBlank(su.getWxOpenId())){
		            		WxMpMsgForm msgForm = new WxMpMsgForm();
		            		msgForm.setWxId(su.getWxId());
		            		msgForm.setAppId(su.getAppId());
		            		msgForm.setOpenId(su.getWxOpenId());
		            		Map<String,String> dataMap = new HashMap<>();
		            		dataMap.put("first", "您好，您收到一个队伍通知");
		            		dataMap.put("keyword1", su.getNickName());
		            		dataMap.put("keyword2", DateUtil.now());
		            		dataMap.put("keyword3", "您的组队已完成，请立即查看");
		            		dataMap.put("remark", "本条信息是站内信通知，祝您游戏愉快！点击查看详情");
		            		msgForm.setDataMap(dataMap);
		            		msgForm.setPage("pages/index/home?my=true&homeId="+home.getId());
		            		wxMsgService.sendTemplateMsg(msgForm);
		            	}
		            }
				}
			}
			
			// 通知房主
			SysUser su = sysUserService.getById(home.getUserId());
			if(StringUtils.isNotBlank(su.getAppId())){
            	if(StringUtils.isNotBlank(su.getWxOpenId())){
            		WxMpMsgForm msgForm = new WxMpMsgForm();
            		msgForm.setWxId(su.getWxId());
            		msgForm.setAppId(su.getAppId());
            		msgForm.setOpenId(su.getWxOpenId());
            		Map<String,String> dataMap = new HashMap<>();
            		dataMap.put("first", "您好，您收到一个队伍通知");
            		dataMap.put("keyword1", user.getNickName());
            		dataMap.put("keyword2", DateUtil.now());
            		dataMap.put("keyword3", "我刚刚加入了你的队伍，请点击查看");
            		dataMap.put("remark", "本条信息是站内信通知，祝您游戏愉快！点击查看详情");
            		msgForm.setDataMap(dataMap);
            		msgForm.setPage("pages/index/home?my=true&homeId="+home.getId());
            		wxMsgService.sendTemplateMsg(msgForm);
            	}
            }
			
		}else{
			if(userGame.getStatus().equals("1")){
				throw new ServiceException("你已被移出队伍");
			}else{
				throw new ServiceException("已在队伍");
			}
		}
	}
	
}
